package org.lzy.shop.base

import android.os.Bundle
import android.view.LayoutInflater
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 * @desc   DataBinding+ViewModel基类
 */
abstract class BaseMvvmActivity<DB: ViewBinding,VM: ViewModel>(block: (LayoutInflater) -> DB) : BaseActivity<DB>(block) {
    lateinit var mViewModel: VM


    override fun onCreate(savedInstanceState: Bundle?) {
        initViewModel()
        super.onCreate(savedInstanceState)
    }

    fun initViewModel() {
        try {
            val argument = (this.javaClass.genericSuperclass as? ParameterizedType)?.actualTypeArguments
            if (argument != null && argument.size > 1 && argument[1] is Class<*>) {
                mViewModel = ViewModelProvider(this).get(argument[1] as Class<VM>)
            } else {
                throw IllegalArgumentException("ViewModel类型参数无效，请检查泛型声明")
            }
        } catch (e: Exception) {
            // 可以添加日志记录或错误处理
            throw RuntimeException("初始化ViewModel失败", e)
        }
   }
}